package com.xclink.app.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xclink.app.entity.Token;
import com.xclink.app.mapper.TokenMapper;
import com.xclink.common.service.AbstractService;

import tk.mybatis.mapper.common.Mapper;

/**
 * 获取本地access_token,超时就自动刷新,但是本地无法检测token是否失效
 * 
 * @author ljp
 *
 */
@Service
public class TokenService extends AbstractService<Token> {
	@Autowired
	private TokenMapper mapper;
	@Autowired
	WxTokenService wxTokenService;

	@Override
	public Mapper<Token> getMapper() {
		return mapper;
	}

	@Override
	public List<Token> find(Token record) {
		return mapper.select(record);
	}

	// 获取本地accesstoken
	public String LocalAccessToken() {
		Date date = new Date();
		Token t = get(1L);
		if (t != null) {
			if (t.getAccessToken() != null && !t.getAccessToken().equals("")) {
				Date updateTime = t.getLastUpdateTime();
				Long time = date.getTime() - updateTime.getTime();
				// 如果时间差超过7000*1000毫秒，那么重新获取微信服务器的accesstoken并存到数据库中
				if (time > 7000000) {
					String access_token = wxTokenService.getAccessToken();
					// 存在数据库中并返回
					updateAccessToken(access_token, date);
					return access_token;
				} else {
					return t.getAccessToken();
				}
			} else {
				// 不存在accesstoken，从微信服务器中获取
				String access_token = wxTokenService.getAccessToken();
				// 存在数据库中并返回
				updateAccessToken(access_token, date);
				return access_token;
			}
		} else {
			// 没存时获取
			String access_token = wxTokenService.getAccessToken();
			addAccessToken(access_token, date);
			return access_token;
		}

	}

	// 存储access_token
	public void addAccessToken(String access_token, Date date) {
		Token entity = new Token();
		entity.setAccessToken(access_token);
		entity.setTokenId(1L);
		entity.setLastUpdateTime(date);
		entity.setCreateTime(date);
		mapper.insert(entity);
	}

	// 更新access_token
	public void updateAccessToken(String access_token, Date date) {
		Token entity = new Token();
		entity.setAccessToken(access_token);
		entity.setTokenId(1L);
		entity.setLastUpdateTime(date);
		mapper.updateByPrimaryKeySelective(entity);
	}

}
